from django.shortcuts import render
from django.http import JsonResponse
from . import serializers
from rest_framework.viewsets import ViewSet
from utils.response import APIResponse
from rest_framework.decorators import action
from user import models
from user.throttles import SMSRateThrottle
from libs.tx_sms import send
from django.core.cache import cache
from django.conf import settings
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin
from rest_framework.generics import ListAPIView
import re


def test(request):
    obj = JsonResponse({'name': 'arther'})
    # obj['Access-Control-Allow-Origin']='*'  # 这是代表可以允许所有的不同域，安全级别较低
    obj['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8001'
    if request.method == 'OPTIONS':
        obj["Access-Control-Allow-Headers"] = 'name'  # 如果有多个请求头，不要再写一个不然会覆盖，在'name,'后继续写即可
    return obj  #


# Create your views here.


class LoginViewSet(ViewSet):
    # 局部禁用
    # 认证组件
    authentication_classes = ()
    # 权限组件
    permission_classes = ()

    def login(self, request, *args, **kwargs):
        print('login')
        # 将request传给序列化器，使序列化器内部得到头像地址

        ser = serializers.LoginSerializer(data=request.data, context={'request': request})

        if ser.is_valid():
            print(ser.data)
            print(ser.context)
            token = ser.context.get('token')
            username = ser.context.get('user').username
            icon = ser.context.get('icon')
            return APIResponse(status=0, token=token, username=username, icon=icon, msg='登录成功')
        else:
            return APIResponse(status=1, msg=ser.errors)

    def check_telephone(self, request, *args, **kwargs):
        import re
        telephone = request.GET.get('telephone')
        print(telephone)
        # 判断手机格式是否正确
        if not re.match('^1[3-9][0-9]{9}$', telephone):
            return APIResponse(status=1, msg='手机号不合法')

        else:
            if models.User.objects.filter(mobile=telephone):
                return APIResponse(result=True, msg='该手机号已存在')

            else:
                return APIResponse(result=False)


class SMSViewSet(ViewSet):
    # 设置访问频率
    throttle_classes = [SMSRateThrottle, ]

    def send(self, request, *args, **kwargs):
        # 验证手机格式
        mobile = request.GET.get('mobile')
        print(mobile)
        if not mobile:
            return APIResponse(status=1, msg='输入为空，请重新输入')
        if not re.match(r'^1[3-9][0-9]{9}$', mobile):
            return APIResponse(status=1, msg='输入格式不正确，请重新输入')

        # 生成四位验证码
        code = send.get_codes()
        # 将验证码套入短信模板
        result = send.send_message(mobile, code)
        if result:
            cache.set(settings.SMS_CACHE_KEY % {'mobile': mobile}, code, settings.SMS_CACHE_TIME)
        return APIResponse(result=result, msg='验证码发送成功')


class SMSLoginViewSet(ViewSet):
    authentication_classes = ()
    permission_classes = ()

    def login(self, request, *args, **kwargs):
        ser = serializers.MobileLoginSerializer(data=request.data, context={'request': request})
        if ser.is_valid():
            token = ser.context.get('token')
            username = ser.context.get('user').username
            user_id = ser.context.get('user').id
            icon = ser.context.get('icon')
            return APIResponse(status=0, token=token, username=username, icon=icon, msg='登录成功', id=user_id)
        else:
            return APIResponse(status=1, msg='登录失败')


class SMSRegisterViewSet(GenericViewSet, CreateModelMixin):
    queryset = models.User.objects.all()
    serializer_class = serializers.SMSRegisterSerializer

    # create方法派生
    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)  # 里面包含了序列化对象序列化的操作
        return APIResponse(data=response.data, http_status=response.status_code, msg='注册成功')
